﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
// Copyright (C) 2021 kingerrobot
// 版权所有。 
//
// 文件名：BWmsOutOrderMaster
// 文件功能描述：
//
// 创建者：名字 (zzl)
// 时间：2021/12/21 15:55:51
//
// 修改人：
// 时间：
// 修改说明：
// 版本：V1.0.0
//----------------------------------------------------------------*/
#endregion
using KingerRobot.MexicoSailunMDC.Dao;
using System.Threading.Tasks;

namespace KingerRobot.MexicoSailunWMS.SpiService;

internal class BWmsOutOrderMaster : IWmsOutOrderMaster
{
    private readonly static IWmsOutOrderSummary _WmsOutOrderSummary = new BWmsOutOrderSummary();
    private readonly static IBakWmsOutOrderMaster _BakWmsOutOrderMaster = new BBakWmsOutOrderMaster();
    private readonly static IWmsOutOrderDetail _WmsOutOrderDetail = new BWmsOrderOrderDetail();
    private readonly static IProdSkuProduct _ProdSkuProduct = new BProdSkuProduct();
    private readonly static IWmsOutOrderSummarySafe _WmsOutOrderSummarySafe = new BWmsOutOrderSummarySafe();
    private readonly static IWcsEquipLoc _WcsEquipLoc = new BWcsEquipLoc();
    private readonly static IRcsEquipCuring _RcsEquipCuring = new BRcsEquipCuring();

    public int UpdateOutOrderFinish(long id, int finishMode)
    {
        var num = UpdateOutOrderMasterFinish(id, finishMode);

        var num1 = _WmsOutOrderSummary.UpdateOutOrderSummaryFinish(id, finishMode);

        return num & num1;
    }
    public int OutOrderFinish(POWcsTask task)
    {
        WriteLog($"人工完成aaa{task.TaskNo},111", true);
        if (task == null)
        {
            return 0;
        }
        WriteLog($"人工完成aaa{task.TaskNo},111", true);
        var id = task.MasterId ?? 0;
        var summaryId = task.SummaryId ?? 0;
        var skuId = task.SkuId ?? 0;
        WriteLog($"人工完成aaa{task.TaskNo},112", true);
        var master = GetOutOrderMasterById(id);
        WriteLog($"人工完成aaa{task.TaskNo},113", true);
        if (master == null)
        {
            WriteLog($"人工完成aaa{task.TaskNo},114", true);
            return 0;
        }

        WriteLog($"人工完成aaa{task.TaskNo},115", true);
        var result = 0;
        var summary = _WmsOutOrderSummary.GetOutOrderSummaryById(summaryId);
        WriteLog($"人工完成aaa{task.TaskNo},116", true);
        if (summary is not null)
        {
            WriteLog($"人工完成aaa{task.TaskNo},117", true);

            var loc = summary?.TargetLoc ?? 0L;
            WriteLog($"人工完成aaa{task.TaskNo},118", true);
            var equip = _WcsEquipLoc.GetEquipIdByLocId(loc);
            WriteLog($"人工完成aaa{task.TaskNo},119", true);
            var curing = _RcsEquipCuring.GetCuringById(equip);
            WriteLog($"人工完成aaa{task.TaskNo},120", true);
            var isCuringCall = curing?.IsCuringCall ?? 0;
            WriteLog($"人工完成aaa{task.TaskNo},121", true);
            // 异常信号 / 
            if (summary.Safe == 0 || (task?.TaskType == (int)EnumTaskType.Abnormal && isCuringCall != 0))
            {
                WriteLog($"人工完成aaa{task.TaskNo},122", true);
                _WmsOutOrderSummarySafe.AddOutOrderSumarySafe(summary.Id.GetValueOrDefault(),
                    summary.TargetLoc.GetValueOrDefault(),
                    summary.Safe.GetValueOrDefault());
            }
            WriteLog($"人工完成aaa{task.TaskNo},123", true);
            _WmsOutOrderSummary.UpdateOutOrderSummaryFinish(summaryId, (int)EnumCodeFinishMode.ManualEnd);
            WriteLog($"人工完成aaa{task.TaskNo},124", true);
            // 获取 Sku 信息
            var sku = _ProdSkuProduct.GetProdSkuProductBySkuId(skuId);
            WriteLog($"人工完成aaa{task.TaskNo},125", true);
            // 订单明细添加
            //result += _WmsOutOrderDetail.AddWmsOutOrderDetail(new()
            //{
            //    Id = XID.Nextval,// 雪花算法 分布式ID
            //    MasterId = task.MasterId,
            //    SummaryId = task.SummaryId,
            //    TaskId = task.Id,
            //    TaskNo = task.TaskNo,

            //    StartLoc = task.StartLoc,
            //    TargetLoc = task.TargetLoc,
            //    SkuId = task.SkuId,
            //    ProductId = sku?.ProductId,

            //    FinishMode = (int)EnumCodeFinishMode.ManualEnd,
            //    FinishTime = DateTime.Now,
            //});
            WriteLog($"人工完成aaa{task.TaskNo},126", true);
            // 数据明细 备份删除
            result += _WmsOutOrderSummary.BakAndDeleteOutOrderSummary(summary.Id ?? 0);
            WriteLog($"人工完成aaa{task.TaskNo},127", true);
        }
        if (!_WmsOutOrderSummary.IsOutOrderSummaryByMasterId(master.Id ?? 0))
        {
            WriteLog($"人工完成aaa{task.TaskNo},128", true);

            // 修改完成状态
            UpdateOutOrderFinish(id, (int)EnumCodeFinishMode.ManualEnd);
            WriteLog($"人工完成aaa{task.TaskNo},129", true);
            // 主数据备份 删除
            result += BakAndDeleteOutOrderMaster(master);
        }

        return result;
    }
    public int BakOutOderMaster(POWmsOutOrderMaster wmsOutOrderMaster)
    {
        if (_BakWmsOutOrderMaster.GetBakWmsOutOrderMasterById(wmsOutOrderMaster.Id.GetValueOrDefault()) != null)
        {
            return 0;
        }
        var db = Db.Default;
        var result = 0;
        try
        {
            result = db.BakWmsOutOrderMasters.CopyFrom(wmsOutOrderMaster);
        }
        catch (Exception ex)
        {

        }
        return result;
    }
    public int BakAndDeleteOutOrderMaster(POWmsOutOrderMaster pOWmsOutOrderMaster)
    {
        var result = BakOutOderMaster(pOWmsOutOrderMaster);
        var id = pOWmsOutOrderMaster.Id.GetValueOrDefault();
        result += DeleteOutOderMaster(id);

        return result;
    }

    public int BakAndDeleteOutOrderMasterAndSummary(long masterId)
    {

        var db = Db.Default;
        //备份并删除出库单
        //删除从表
        var summaryList = db.WmsOutOrderSummarys.Where(t => t.MasterId == masterId).ToList();
        foreach (var summary in summaryList)
        {
            _WmsOutOrderSummary.BakAndDeleteOutOrderSummary(summary.Id ?? 0);
        }
        //删除主表
        var master = db.WmsOutOrderMasters.Where(t => t.Id == masterId).FirstOrDefault() ?? new POWmsOutOrderMaster();
        var result = BakAndDeleteOutOrderMaster(master);
        return result;
    }

    public List<POWmsOutOrderMaster> GetOutOrderMasterByIds(List<long?> ids)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderMasters.Where(t => ids.Contains(t.Id)).ToList();
        return result;
    }
    public POWmsOutOrderMaster GetOutOrderMasterById(long id)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderMasters.Where(t => t.Id == id).FirstOrDefault();
        return result;
    }
    public List<POWmsOutOrderMaster> GetOutOrderMasterList()
    {
        var db = Db.Default;
        var result = db.WmsOutOrderMasters.Join(db.WmsOutOrderSummarys, f => f.Id, s => s.MasterId, (f, s) => f).ToList();
        return result;
    }
    public List<POWmsOutOrderSummary> GetOutOrderSummaryList()
    {
        var db = Db.Default;
        var result = db.WmsOutOrderSummarys.ToList();
        return result;
    }
    public List<POVLocationOut> GetLocaltionOutList()
    {
        var db = Db.Default;
        var result = db.VLocationOut.ToList();
        return result;
    }
    public List<POVOutFollow> GetOutFollowList()
    {
        var db = Db.Default;
        var result = db.VOutFollows.ToList();
        return result;
    }
    public List<POVInFollow> GetInFollowList()
    {
        var db = Db.Default;
        var result = db.VInFollow.ToList();
        return result;
    }
    public List<OutOrderMasterSummarys> GetOutOrderMasterSummaryList()
    {
        var db = Db.Default;
        var masters = db.WmsOutOrderMasters.ToList();
        var summarys = db.WmsOutOrderSummarys.ToList();
        var summaryMasters = summarys.Join(masters, f => f.MasterId, s => s.Id, (f, s) => new OutOrderMasterSummarys
        {
            MasterId = s.Id.GetValueOrDefault(),
            StartLoc = f.StartLoc.GetValueOrDefault(),
            TargetLoc = f.TargetLoc.GetValueOrDefault(),
            MaterialId = f.MaterialId.GetValueOrDefault(),
            FinishMode = f.FinishMode.GetValueOrDefault(),
            OrderType = s.OrderType.GetValueOrDefault(),
            OrderCode = s.OrderCode,
            OrderStatus = s.OrderStatus.GetValueOrDefault(),
            OrderPriority = s.OrderPriority.GetValueOrDefault(),
            CreateTime = s.CreateTime.GetValueOrDefault(),
            PlanCount = f.PlanCount,
            RealCount = f.RealCount,
            Remark = f.RemarkMemo,
        }).ToList();
        return summaryMasters;
    }

    public long AddOutOrderMaster(int orderType, string outType = "", int priority = 12)
    {
        var db = Db.Default;
        var orderId = XID.Nextval;
        var num = db.WmsOutOrderMasters.Insert(new POWmsOutOrderMaster()
        {
            Id = orderId,
            OrderCode = K8.LSF.Client.CodeValue(new DateTime(), "OutOrder"),
            OrderType = orderType, //OLDTODO【已解决】李声强 硫化请料（Enum）
            OrderStatus = (int)EnumCodeOutOrderStatus.Create, //OLDTODO【已解决】李声强 创建（Enum）
            RemarkMemo = outType == "2" ? "线体手工出库" : "立库手工出库",
        });
        if (num == 0)
        {
            return 0;
        }
        return orderId;
    }
    public int DeleteOutOderMaster(long? id)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderMasters.Where(t => t.Id == id).Delete();
        return result;
    }


    public int UpdateOutOrderMasterFinish(long id, int finishMode)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderMasters.Where(t => t.Id == id).Update(new POWmsOutOrderMaster
        {
            FinishMode = finishMode,
            FinishTime = DateTime.Now,
        });
        return result;
    }


    public int UpdateMasterStatus(long id, int status)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderMasters.Where(t => t.Id == id).Update(new POWmsOutOrderMaster
        {
            OrderStatus = status,
            UpdateTime = DateTime.Now,
        });
        return result;
    }

    public int BakAndDeleteOutOrderByTask(POWcsTask task)
    {
        var db = Db.Default;
        var masterId = task.MasterId;

        var result = 0;
        var summaryList = db.WmsOutOrderSummarys.Where(t => t.MasterId == masterId).ToList();
        var summaryId = summaryList.Where(t => t.Id == task.SummaryId).FirstOrDefault()?.Id ?? 0;
        //证明是单模请料 删除主从表信息
        if (summaryList is not null && summaryList.Count == 1)
        {    //删除从表
            _WmsOutOrderSummary.BakAndDeleteOutOrderSummary(summaryId);
            //删除主表
            var master = db.WmsOutOrderMasters.Where(t => t.Id == masterId).FirstOrDefault() ?? new POWmsOutOrderMaster();
            result = BakAndDeleteOutOrderMaster(master);
        }
        else//双模请料  只删除对应的从表信息
        {
            result = _WmsOutOrderSummary.BakAndDeleteOutOrderSummary(summaryId);
        }
        return result;
    }

    public int BakAndDeleteOutOrderBySummaryId(long masterId, long summaryId)
    {
        var db = Db.Default;

        var result = 0;
        var summaryList = db.WmsOutOrderSummarys.Where(t => t.MasterId == masterId).ToList();

        //证明是单模请料 删除主从表信息
        if (summaryList.Count == 1)
        {    //删除从表
            _WmsOutOrderSummary.BakAndDeleteOutOrderSummary(summaryId);
            //删除主表
            var master = db.WmsOutOrderMasters.Where(t => t.Id == masterId).FirstOrDefault() ?? new POWmsOutOrderMaster();
            result = BakAndDeleteOutOrderMaster(master);
        }
        else//双模请料  只删除对应的从表信息
        {
            result = _WmsOutOrderSummary.BakAndDeleteOutOrderSummary(summaryId);
        }
        return result;
    }

}

